<?php

namespace common\components\fs;

use common\components\wtools\tools\FileHelper;
use common\components\wtools\tools\Model;

class LocalFs extends Fs
{
    public static function getComponentId(): string
    {
        return 'localFs';
    }

    protected $path;
    protected $pathRoot;
    protected $pathUri;
    protected $pathAburi;

    public function init()
    {
        parent::init();
        if (!$this->path) {
            $this->path = 'native/'.date('Y/m/d');
        }
        $this->setPath($this->path);
    }

    public function setPath($path)
    {
        $this->path = $path;
        $this->pathRoot = \Yii::getAlias('@uploads_root').'/'.$path;
        $this->pathUri = \Yii::getAlias('@uploads_url').'/'.$path;
        $this->pathAburi = \Yii::getAlias('@uploads_aburl').'/'.$path;
        if (!is_dir($this->pathRoot)) {
            FileHelper::createDirectory($this->pathRoot);
        }
    }

    public function uploadBase64($idFileName, $base64Content)
    {
        file_put_contents($this->pathRoot."/".$idFileName, $base64Content);
        $url = $this->pathAburi."/".$idFileName;
        return $url;
    }

    public function saveFile()
    {
        $this->file->locate_path = $this->path;
        if (!$this->file->save()) {
            throw new \Exception("文件保存失败：".Model::getModelError($this->file));
        }
        return $this->file;
    }

    /**
     * @return string
     */
    public function getAbUrl()
    {
        return \Yii::getAlias('@uploads_aburl').'/'.$this->file->locate_path.'/'.$this->file->filename;
    }
}
